package com.study.talk.app.group;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;


import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.study.talk.adapter.MyRecycleViewAdapter;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.app.friend.UserInfoActivity;
import com.study.talk.databinding.ActivityGroupInfoBinding;
import com.study.talk.databinding.UserListItemBinding;
import com.study.talk.entity.GroupInfo;
import com.study.talk.entity.resp.BoolResponse;
import com.study.talk.entity.resp.GroupUserInfoResponse;
import com.study.talk.entity.vo.GroupUserInfoVo;
import com.study.talk.net.NetApi;
import com.study.talk.netty.NettyClient;
import com.study.talk.netty.message.request.ApplyGroupRequest;
import com.study.talk.netty.message.response.ApplyGroupSelfResponse;
import com.study.talk.util.AppExecutor;
import com.study.talk.util.DateUtil;
import com.study.talk.util.GsonInstance;
import com.study.talk.util.ListViewUtil;
import com.study.talk.net.OkHttp;
import com.study.talk.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.netty.util.internal.StringUtil;

public class GroupInfoActivity extends BaseActivity {

    private GroupInfo groupInfo;

    private ActivityGroupInfoBinding activityGroupInfoBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityGroupInfoBinding = ActivityGroupInfoBinding.inflate(getLayoutInflater());
        setContentView(activityGroupInfoBinding.getRoot());

        setSupportActionBar(activityGroupInfoBinding.groupInfoToolbar);

        groupInfo = GsonInstance.instance.fromJson(getIntent().getStringExtra("data"), GroupInfo.class);

        initView();
    }


    @SuppressLint("SetTextI18n")
    private void initView() {

        activityGroupInfoBinding.groupInfoToolbar.setTitle(groupInfo.getName());
        activityGroupInfoBinding.groupInfoToolbar.setNavigationOnClickListener(v -> finish());

        Glide.with(GroupInfoActivity.this).load(OkHttp.URL + groupInfo.getAvatar()).into(activityGroupInfoBinding.groupInfoHeadImg);

        if (!StringUtil.isNullOrEmpty(groupInfo.getBgImg())) {
            Glide.with(GroupInfoActivity.this).load(OkHttp.URL + groupInfo.getBgImg()).into(activityGroupInfoBinding.groupInfoBgImg);
        }

        activityGroupInfoBinding.groupInfoName.setText(groupInfo.getName());

        NetApi.getUserInfo(groupInfo.getMainUser(), user -> {
            runOnUiThread(() -> activityGroupInfoBinding.groupInfoMainUser.setText("管理员：" + user.getUsername()));
        }, msg -> runOnUiThread(() -> ToastUtil.showToast(GroupInfoActivity.this, msg)));

        activityGroupInfoBinding.groupInfoListView.setAdapter(new ArrayAdapter<>(GroupInfoActivity.this, android.R.layout.simple_list_item_1, createListViewData()));
        ListViewUtil.setHeight(activityGroupInfoBinding.groupInfoListView);


        activityGroupInfoBinding.groupInfoAddBt.setOnClickListener(view -> {
            ApplyGroupRequest request = new ApplyGroupRequest(groupInfo.getId());
            request.setDateTime(DateUtil.getCurrentTime());
            NettyClient.sendMessage(request);
            showLoadingDialog();
        });

        //获取群聊信息
        OkHttp.get("/groupUserInfo/get/user/list/" + groupInfo.getId(), res -> {
            GroupUserInfoResponse response = GsonInstance.instance.fromJson(res, GroupUserInfoResponse.class);

            List<GroupUserInfoResponse.Data> dataList = response.getData();

            MyRecycleViewAdapter<GroupUserInfoResponse.Data, ViewHolder> recycleViewAdapter = new MyRecycleViewAdapter<>(dataList, this) {
                @NonNull
                @Override
                public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    return new ViewHolder(UserListItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
                }

                @Override
                public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
                    GroupUserInfoResponse.Data userInfo = data.get(position);
                    Glide.with(activity).load(OkHttp.URL + userInfo.getUserAvatar()).into(holder.itemBinding.userListItemHeadImg);
                    holder.itemBinding.userListItemHeadUsername.setText(userInfo.getUserName());
                    holder.itemBinding.userListItemHeadIntroduce.setText(userInfo.getUserIntroduce());

                    //点击群信息中的成员跳转到成员详情
                    holder.itemBinding.getRoot().setOnClickListener(v -> {
                        int userId = data.get(position).getUserId();
                        Intent intent = new Intent(activity, UserInfoActivity.class);
                        intent.putExtra("userId", userId);
                        startActivity(intent);
                    });
                }
            };

            AppExecutor.getInstance().MAIN_HANDLER().post(() -> {
                activityGroupInfoBinding.groupInfoUserListView.setLayoutManager(new LinearLayoutManager(this));
                activityGroupInfoBinding.groupInfoUserListView.setAdapter(recycleViewAdapter);
            });
        });


        //如果已经在群里中，则不显示加入群聊按钮
        OkHttp.post("/groupUserInfo/query/has/member", GsonInstance.instance.toJson(new GroupUserInfoVo(groupInfo.getId(), getApp().userId())), res -> {
            BoolResponse response = GsonInstance.instance.fromJson(res, BoolResponse.class);
            if (response.getData()) {
                runOnUiThread(() -> activityGroupInfoBinding.groupInfoAddBt.setVisibility(View.GONE));
            }
        });
    }


    //申请加入群聊消息发送成功会根据EventBus的消息分发来到这
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddUserSelfResponseMessage(ApplyGroupSelfResponse applyGroupSelfResponse) {
        dismissLoadingDialog();
        if (applyGroupSelfResponse.getSuccess()) {
            ToastUtil.showToast(GroupInfoActivity.this, "加入群聊请求发送成功!");
        } else {
            ToastUtil.showToast(GroupInfoActivity.this, "发送失败:" + applyGroupSelfResponse.getReason());
        }
    }

    private List<String> createListViewData() {
        List<String> listViewData = new ArrayList<>();
        listViewData.add("群聊标签：" + groupInfo.getTag());
        listViewData.add("群聊简介：" + groupInfo.getIntroduce());
        return listViewData;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public UserListItemBinding itemBinding;

        public ViewHolder(UserListItemBinding itemBinding) {
            super(itemBinding.getRoot());
            this.itemBinding = itemBinding;
        }
    }
}